package com.huawei.hms.common.internal;

import android.content.Context;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;
import com.huawei.hms.api.Api.ApiOptions;
import com.huawei.hms.api.ConnectionResult;
import com.huawei.hms.api.HuaweiApiAvailability;
import com.huawei.hms.common.HuaweiApi;
import com.huawei.hms.common.internal.AnyClient.CallBack;
import com.huawei.hms.common.internal.BaseHmsClient.ConnectionCallbacks;
import com.huawei.hms.common.internal.BaseHmsClient.OnConnectionFailedListener;
import com.huawei.hms.core.aidl.IMessageEntity;
import com.huawei.hms.support.api.entity.core.CommonCode.ErrorCode;
import com.huawei.hms.support.hianalytics.HiAnalyticsConstant;
import com.huawei.hms.support.hianalytics.b;
import com.huawei.hms.support.log.HMSLog;
import com.huawei.hms.utils.Checker;
import java.util.LinkedList;
import java.util.Map;
import java.util.Queue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
import o.fjx;

public class HuaweiApiManager implements Callback {
    private static final Object a = new Object();
    private static HuaweiApiManager b;
    private final Handler c;
    private final AtomicInteger d = new AtomicInteger(0);
    private final Map<ConnectionManagerKey<?>, ConnectionManager<?>> e = new ConcurrentHashMap(5, 0.75f, 1);

    public class ConnectionManager<OptionsT extends ApiOptions> implements ConnectionCallbacks, OnConnectionFailedListener {
        final /* synthetic */ HuaweiApiManager a;
        private final Queue<a> b = new LinkedList();
        private final AnyClient c;
        private ConnectionResult d;
        private final ConnectionManagerKey e;
        private final HuaweiApi<OptionsT> f;

        ConnectionManager(HuaweiApiManager huaweiApiManager, HuaweiApi<OptionsT> huaweiApi) {
            this.a = huaweiApiManager;
            this.f = huaweiApi;
            this.c = huaweiApi.getClient(huaweiApiManager.c.getLooper(), this);
            this.d = null;
            this.e = huaweiApi.getConnectionManagerKey();
        }

        void a(TaskApiCallWrapper taskApiCallWrapper) {
            HMSLog.i("HuaweiApiManager", "sendRequest");
            Checker.assertHandlerThread(this.a.c);
            a b = b(taskApiCallWrapper);
            if (this.c.isConnected()) {
                a(b);
                return;
            }
            this.b.add(b);
            if (this.d == null || this.d.getErrorCode() == 0) {
                b();
            } else {
                onConnectionFailed(this.d);
            }
        }

        private String a(String str, String str2) {
            if (TextUtils.isEmpty(str)) {
                return TransactionIdCreater.getId(this.f.getAppID(), str2);
            }
            return str;
        }

        private void a(a aVar) {
            String uri = aVar.a().getTaskApiCall().getUri();
            IMessageEntity requestHeader = new RequestHeader();
            requestHeader.setSrvName(uri.split("\\.")[0]);
            requestHeader.setApiName(uri);
            requestHeader.setAppID(this.f.getAppID() + HiAnalyticsConstant.REPORT_VAL_SEPARATOR + this.f.getSubAppID());
            requestHeader.setPkgName(this.f.getContext().getPackageName());
            requestHeader.setSessionId(this.c.getSessionId());
            TaskApiCall taskApiCall = aVar.a().getTaskApiCall();
            requestHeader.setTransactionId(a(taskApiCall.getTransactionId(), uri));
            requestHeader.setParcelable(taskApiCall.getParcelable());
            requestHeader.setKitSdkVersion(this.f.getKitSdkVersion());
            this.c.post(requestHeader, taskApiCall.getRequestJson(), aVar.b());
        }

        private a b(final TaskApiCallWrapper taskApiCallWrapper) {
            return new a(taskApiCallWrapper, new CallBack(this) {
                final /* synthetic */ ConnectionManager b;

                public void onCallback(IMessageEntity iMessageEntity, String str) {
                    if (iMessageEntity instanceof ResponseHeader) {
                        ResponseHeader responseHeader = (ResponseHeader) iMessageEntity;
                        if (!TextUtils.isEmpty(responseHeader.getResolution())) {
                            HMSLog.e("HuaweiApiManager", "Response has resolution: " + responseHeader.getResolution());
                        }
                        b.a(this.b.f.getContext(), responseHeader, String.valueOf(this.b.f.getKitSdkVersion()));
                        taskApiCallWrapper.getTaskApiCall().doExecute(this.b.c, responseHeader, str, taskApiCallWrapper.getTaskCompletionSource());
                        return;
                    }
                    HMSLog.e("HuaweiApiManager", "header is not instance of ResponseHeader");
                }
            });
        }

        boolean a() {
            Checker.assertHandlerThread(this.a.c);
            this.c.disconnect();
            return true;
        }

        synchronized void b() {
            Checker.assertHandlerThread(this.a.c);
            if (this.c.isConnected()) {
                HMSLog.d("HuaweiApiManager", "client is connected");
            } else if (this.c.isConnecting()) {
                HMSLog.d("HuaweiApiManager", "client is isConnecting");
            } else {
                this.c.connect();
            }
        }

        private void a(ConnectionResult connectionResult) {
            Checker.assertHandlerThread(this.a.c);
            this.d = connectionResult;
            for (a a : this.b) {
                TaskApiCallWrapper a2 = a.a();
                ResponseErrorCode responseHeader = new ResponseHeader(1, ErrorCode.CLIENT_API_INVALID, "Connection Failed");
                responseHeader.setTransactionId(a2.getTaskApiCall().getTransactionId());
                a2.getTaskApiCall().doExecute(this.c, responseHeader, null, a2.getTaskCompletionSource());
            }
            this.b.clear();
            this.d = null;
            this.c.disconnect();
            this.a.e.remove(this.e);
        }

        public void onConnectionFailed(final ConnectionResult connectionResult) {
            HMSLog.i("HuaweiApiManager", "onConnectionFailed");
            if (Looper.myLooper() == this.a.c.getLooper()) {
                a(connectionResult);
            } else {
                this.a.c.post(new Runnable(this) {
                    final /* synthetic */ ConnectionManager b;

                    public void run() {
                        this.b.a(connectionResult);
                    }
                });
            }
        }

        private void c() {
            Checker.assertHandlerThread(this.a.c);
            this.d = null;
            for (a a : this.b) {
                a(a);
            }
            this.b.clear();
        }

        public void onConnected() {
            HMSLog.d("HuaweiApiManager", "onConnected");
            if (Looper.myLooper() == this.a.c.getLooper()) {
                c();
            } else {
                this.a.c.post(new Runnable(this) {
                    final /* synthetic */ ConnectionManager a;

                    {
                        this.a = r1;
                    }

                    public void run() {
                        this.a.c();
                    }
                });
            }
        }

        private void a(int i) {
            Checker.assertHandlerThread(this.a.c);
            for (a a : this.b) {
                TaskApiCallWrapper a2 = a.a();
                ResponseErrorCode responseHeader = new ResponseHeader(1, ErrorCode.CLIENT_API_INVALID, "Connection Suspended");
                responseHeader.setTransactionId(a2.getTaskApiCall().getTransactionId());
                a2.getTaskApiCall().doExecute(this.c, responseHeader, null, a2.getTaskCompletionSource());
            }
            this.b.clear();
            this.d = null;
            this.c.disconnect();
            this.a.e.remove(this.e);
        }

        public void onConnectionSuspended(final int i) {
            HMSLog.i("HuaweiApiManager", "onConnectionSuspended");
            if (Looper.myLooper() == this.a.c.getLooper()) {
                a(i);
            } else {
                this.a.c.post(new Runnable(this) {
                    final /* synthetic */ ConnectionManager b;

                    public void run() {
                        this.b.a(i);
                    }
                });
            }
        }
    }

    static class a {
        private final TaskApiCallWrapper a;
        private final CallBack b;

        a(TaskApiCallWrapper taskApiCallWrapper, CallBack callBack) {
            this.a = taskApiCallWrapper;
            this.b = callBack;
        }

        TaskApiCallWrapper a() {
            return this.a;
        }

        CallBack b() {
            return this.b;
        }
    }

    private HuaweiApiManager(Context context, Looper looper, HuaweiApiAvailability huaweiApiAvailability) {
        this.c = new Handler(looper, this);
    }

    public static HuaweiApiManager getInstance(Context context) {
        synchronized (a) {
            if (b == null) {
                HandlerThread handlerThread = new HandlerThread("HuaweiApiManager");
                handlerThread.start();
                b = new HuaweiApiManager(context.getApplicationContext(), handlerThread.getLooper(), HuaweiApiAvailability.getInstance());
            }
        }
        return b;
    }

    public final <TOption extends ApiOptions, TResult> void sendRequest(HuaweiApi<TOption> huaweiApi, TaskApiCall<? extends AnyClient, TResult> taskApiCall, fjx<TResult> o_fjx_TResult) {
        this.c.sendMessage(this.c.obtainMessage(4, new b(new TaskApiCallWrapper(taskApiCall, o_fjx_TResult), this.d.getAndIncrement(), huaweiApi)));
    }

    private void a(HuaweiApi<?> huaweiApi, fjx<Boolean> o_fjx_java_lang_Boolean) {
        ConnectionManager connectionManager = (ConnectionManager) this.e.get(huaweiApi.getConnectionManagerKey());
        if (connectionManager == null) {
            o_fjx_java_lang_Boolean.ॱ(Boolean.valueOf(false));
        } else {
            o_fjx_java_lang_Boolean.ॱ(Boolean.valueOf(connectionManager.a()));
        }
    }

    public void disconnectService(HuaweiApi<?> huaweiApi, fjx<Boolean> o_fjx_java_lang_Boolean) {
        if (Looper.myLooper() == this.c.getLooper()) {
            a(huaweiApi, o_fjx_java_lang_Boolean);
        } else {
            this.c.post(new 1(this, huaweiApi, o_fjx_java_lang_Boolean));
        }
    }

    public boolean handleMessage(Message message) {
        switch (message.what) {
            case 4:
                a((b) message.obj);
                return true;
            default:
                HMSLog.w("HuaweiApiManager", "Unknown message id: " + message.what);
                return false;
        }
    }

    private void a(b bVar) {
        ConnectionManager connectionManager;
        HuaweiApi huaweiApi = bVar.b;
        ConnectionManager connectionManager2 = (ConnectionManager) this.e.get(huaweiApi.getConnectionManagerKey());
        if (connectionManager2 == null) {
            connectionManager2 = new ConnectionManager(this, huaweiApi);
            this.e.put(huaweiApi.getConnectionManagerKey(), connectionManager2);
            connectionManager = connectionManager2;
        } else {
            connectionManager = connectionManager2;
        }
        connectionManager.a((TaskApiCallWrapper) bVar.a);
    }
}
